<template lang="pug">
    div(class="forum-post-flow", :class="classes", ref="pf",:style="{height: pagedPanelHeight ? pagedPanelHeight : 'calc(100vh - 45px)'}")
        div(style="background:#fff;padding:10px;text-align:center;width:100%;position:absolute;", 
        v-if="(!paged.items || !paged.items.length) && !query") 没有数据
        better-scroll-vue(class="my-wrapper"
                         ref="scroll"
                         :scrollbar="{fade:true}"
                         :pullDownRefresh="{threshold: 90,stop: 40}"
                         :pullUpLoad="{threshold: 0,txt: {more: '加载更多',noMore: '没有更多数据了'}}"
                         :startY="0"
                         :mouseWheel="mouseWheel"
                         @pullingDown="onPullingDown"
                         @pullingUp="onPullingUp")
            ul(class="content")
                    li(v-for="item in paged.items", class="forum-post-flow__item", @click="toDetail(item)")
                        el-row
                            el-col(:span="3")
                                img(v-if="item.avatar", v-lazy="item.avatar", class="icon forum-post-flow__avatar")
                                span(v-else, v-lazy="item.avatar", class="icon forum-post-flow__avatar")
                            el-col(:span="14")
                                div(class="forum-post-flow__uname")
                                    span(@click.stop="toUserZone(item)") {{item.wxUName}}
                                div(class="forum-post-flow__ctime")
                                    small {{item.postCreateAt | format('YYYY-MM-DD HH:mm')}}
                            el-col(:span="7", style="text-align:right")
                                follow-button(:target-wx-uid="item.wxUId",:is-following.sync="item.followed", @change="followStateChange(item)")
                                el-button(v-if="item.wxUId==currentWxUId",type="text", @click.stop="toTrash(item)")
                                    i(class="el-icon-delete")

                        div(class="forum-post-flow__item__content")
                            div(style="display:inline-block;white-space: pre-line;padding: 3px 0 8px 0;")(v-html="limit_len(item.postContent,90,'[查看全文]', item.postTitle ? `【${item.postTitle}】` : '')")
                            cube(:images="getImages(item.images)")
                        div(class="forum-post-flow__item__social")
                            el-row(type="flex", justify="space-around")
                                el-col(:span="colSpan",v-if="showAccess", class="forum-post-flow__item__social_col")
                                    span {{item.accessCount}}阅读
                                el-col(:span="colSpan", class="forum-post-flow__item__social_col")
                                    a(href="javascript:void(0)",@click.stop="like(item)")
                                        svg(class="icon forum-post-flow__item__social_icon", aria-hidden="true")
                                            use(:xlink:href="item.isLike ? '#icon-like':'#icon-dianzan'")
                                        span {{item.likeCount}}
                                el-col(:span="colSpan", class="forum-post-flow__item__social_col")
                                    a()
                                        svg(class="icon forum-post-flow__item__social_icon", aria-hidden="true")
                                            use(xlink:href="#icon-pinglun")
                                        span {{item.commentCount}}
                                el-col(:span="colSpan", class="forum-post-flow__item__social_col")
                                    a(href="javascript:void(0);",@click.stop="favorite(item)")
                                        svg(class="icon forum-post-flow__item__social_icon", aria-hidden="true")
                                            use(:xlink:href="item.isFavorite ? '#icon-shoucang-' : '#icon-shoucang'")
                                        span 收藏
                                div
                                    lazyload-mark(:data="item",@show="handleAccess")
                                <!-- 用来放置内容详细 -->                                
        active-panel(:visible="activePanelVisible", style="z-index:3", @history-back="postDetailHistoryBack", scroll-y="auto")
            post-detail(:post-id="currentPost.postId")
        active-panel(:visible="zoneVisible", style="z-index:3",@history-back="userZoneHistoryBack")
            zone(:wx-uid="currentPost.wxUId")

</template>

<script>
import axios from "@/plugins/axios";
import BaseVue from "@/mixins/BaseVue";
import cube from "./cube";
import FollowBtn from "@/pages/components/follow-button";
import PagedPanel from "batman-paged-panel";
import store from "@/plugins/store";
import PostDetail from "./detail.vue";
import util from "@/libs/util";
import LazyloadMark from "@/pages/components/lazyload-mark";
import accessStore from "@/store/AccessStore";
import ScrollableStore from "@/store/ScrollableStore";
import Vue from "vue";
import VueBetterScroll from "better-scroll-vue";
console.log(VueBetterScroll)
Vue.use(VueBetterScroll);
import dayjs from "dayjs";

import VueLazyload from "vue-lazyload";

Vue.use(VueLazyload);

import displayContent from "@/plugins/post/display_content_util";

export default {
  name: "post-flow",
  mixins: [BaseVue],
  components: {
    cube: cube,
    "follow-button": FollowBtn,
    "paged-panel": PagedPanel,
    "post-detail": PostDetail,
    "lazyload-mark": LazyloadMark
  },
  data() {
    return {
      paged: { items: [] },
      page: { skipCount: 0, maxResultCount: 10 },
      // 刷新用分页
      refreshPage: { skipCount: 0, maxResultCount: 10 },
      query: false,
      base_url: process.env.NODE_ENV !== "development" ? "/" : "/api/",
      loadCompleted: false,

      activePanelVisible: false,
      currentPost: { postId: null },

      zoneVisible: false,
      maxCreateAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),

      // 初始数据是否已加载
      isInitDataLoad: false,

      mouseWheel: { speed: 20, invert: false, easeTime: 300 }
    };
  },
  props: {
    resource_url: { type: String, default: null },
    /**
     * 自定义样式
     */
    iClass: { type: String, default: null },
    /** 分区过滤 */
    partitionId: { type: String, default: null },
    /**根據作者过滤 */
    "wx-uid": { type: String, default: null },

    /**是否显示访问量 */
    showAccess: { type: Boolean, default: false },

    "paged-panel-height": { type: String, default: "" },

    /** 挂载后是否加请求数据 */
    "load-data-when-mounted": { type: Boolean, default: true }
  },
  computed: {
    classes() {
      const result = {};
      if (this.iClass) result[this.iClass] = true;
      return result;
    },
    filter() {
      return {
        partitionId: this.partitionId,
        createBy: this.wxUid,
        showAccess: this.showAccess
      };
    },
    currentWxUId() {
      return util.cookies.get("wxuid");
    },
    colSpan() {
      return this.showAccess ? 6 : 8;
    }
  },
  methods: {
    getPostFlow(resolve) {
      const url = this.resource_url || "forum/home/postFlow"; // 默认是获取首页的帖子数据
      const excludePost = this.getPostInPaged();
      const filter = Object.assign(
        {
          maxCreateAt: this.maxCreateAt,
          excludePost: excludePost
        },
        this.filter
      );
      const options = {
        url: url,
        method: "post",
        data: { page: this.page, filter: filter }
      };
      this.query = true;
      axios(options)
        .then(paged => this.getPostFlowSuccess(paged, resolve))
        .catch(e => {
          this.query = false;
          resolve(false);
        });
    },
    getPostFlowSuccess(paged, resolve) {
      if (paged.items.length === 0) {
        this.loadCompleted = true;
      } else {
        this.paged.items = this.paged.items.concat(paged.items);
      }

      this.query = false;
      if (resolve) resolve(!this.loadCompleted);
    },
    like(item) {
      const options = {
        url: "forum/home/like",
        method: "post",
        data: { postId: item.postId }
      };
      // 在请求前就需要把item.isLike状态进行改变，从而实现用户看到界面有了点赞的改变。
      // 如果下文中请求服务器失败，则要改回状态
      this.changeLikeState(item);
      axios(options)
        .then(() => this.likeSuccess())
        .catch(() => this.changeLikeState(item));
    },
    changeLikeState(item) {
      item.isLike = !item.isLike;
      item.likeCount = item.isLike ? item.likeCount + 1 : item.likeCount - 1;
    },
    likeSuccess() {},
    favorite(item) {
      const options = {
        url: "forum/favorite/postFavorite",
        method: "post",
        data: { postId: item.postId }
      };
      // 在请求前就需要把item.isFavorite状态进行改变，从而实现用户看到界面有了点赞的改变。
      // 如果下文中请求服务器失败，则要改回状态
      this.changeFavoriteState(item);
      axios(options)
        .then(() => {})
        .catch(() => this.changeFavoriteState(item));
    },
    changeFavoriteState(item) {
      item.isFavorite = !item.isFavorite;
    },
    getImages(images) {
      if (!images) return [];
      return images.map(image => {
        return { url: this.base_url + image };
      });
    },
    toDetail(post) {
      this.currentPost = post;
      ScrollableStore.commit("disable");
      this.activePanelVisible = true;
    },
    toUserZone(post) {
      this.currentPost = post;
      ScrollableStore.commit("disable");
      this.zoneVisible = true;
    },
    followStateChange(post) {
      // 把其他帖子的作者等于这个帖子的作者的状态设为一样
      this.paged.items.forEach(item => {
        if (item.wxUId == post.wxUId) item.followed = post.followed;
      });
    },
    toTrash(post) {
      this.comfirn("确定删除这个帖子吗?")
        .then(this.doTrash.bind(this, post))
        .catch(() => {});
    },
    doTrash(post) {
      const options = {
        url: "forum/post/trashPost",
        method: "post",
        data: { postId: post.postId }
      };
      axios(options)
        .then(this.doTrashSuccess.bind(this, post))
        .catch(() => {});
    },
    doTrashSuccess(post) {
      // 刪除post
      const index = this.paged.items.findIndex(item => {
        return post.postId == item.postId;
      });
      if (index > -1) this.paged.items.splice(index, 1);
    },
    handleAccess(post) {
      accessStore.commit("add_record", post.postId);
    },
    postDetailHistoryBack() {
      this.activePanelVisible = false;
      ScrollableStore.commit("enable"); // 让tab可以切换
    },
    userZoneHistoryBack() {
      this.zoneVisible = false;
      ScrollableStore.commit("enable");
    },
    onPullingDown() {
      this.getNewerPosts(this.$refs.scroll.forceUpdate);
    },
    onPullingUp() {
      this.getPostFlow(this.$refs.scroll.forceUpdate);
    },
    getPostInPaged() {
      return this.paged.items.map(item => {
        return item.postId;
      });
    },
    /**
     * 上拉刷新
     */
    getNewerPosts(resolve) {
      const url = this.resource_url || "forum/home/postFlow"; // 默认是获取首页的帖子数据
      const excludePost = this.getPostInPaged();
      const filter = Object.assign(
        {
          minCreateAt: this.maxCreateAt,
          excludePost: excludePost
        },
        this.filter
      );
      const options = {
        url: url,
        method: "post",
        data: { page: this.refreshPage, filter: filter }
      };
      this.query = true;
      axios(options)
        .then(paged => this.getNewPostsSuccess(paged, resolve))
        .catch(e => {
          this.query = false;
          resolve(false);
        });
    },
    /** 下拉刷新成功 */
    getNewPostsSuccess(paged, resolve) {
      paged.items.forEach(item => this.paged.items.unshift(item));
      resolve(true);
    },
    init() {
      if (this.isInitDataLoad) return; // 只允许初始一次
      this.getPostFlow();
      this.isInitDataLoad = true;
    },
    /**
     * 限制文字长度
     * @param {*} val 原始文字
     * @param {*} len 限制长度
     * @param {*} append 超过的替代
     */
    limit_len: displayContent
  },
  mounted() {
    if (this.loadDataWhenMounted) this.getPostFlow();
  }
};
</script>

<style lang="less" scoped>
@import "../../common/common.less";

.forum-post-flow {
  background-color: transparent;
  min-height: 100%;

  .my-wrapper {
    ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }
  }
  &__avatar {
    @width: 40px;
    width: @width;
    height: @width;
    border-radius: @width;
  }

  &__item {
    padding: 15px 12px 0;
    margin-bottom: 5px;
    background-color: white;

    &__content {
      padding: 8px 0;
    }

    &__social {
      padding: 10px 0;
      border-top: 1px solid #eaeaea;
      margin-top: 5px;

      a {
        text-decoration: none;
        color: inherit;
      }

      &_icon {
        @edage: 1em;
        width: @edage;
        height: @edage;
        margin-right: 5px;
      }

      &_col {
        text-align: center;
      }
    }
  }

  &__uname {
    color: #eb7350;
    font-weight: bold;
  }

  &__ctime {
    color: grey;
  }

  &__avatar {
    @edge: 2.5em;
    width: @edge;
    height: @edge;
  }
}

.page-height {
  height: calc(100vh - 45px - 45px);
}
</style>

<style lang="less">
.forum-post-flow {
  .jb-emotion {
    @height: 24px;
    height: @height;
    width: @height;
  }
}
</style>